
%MACRO patterns(in,out);

*****************************************************************************
* Program: PATTERNS					   						
* 																			
* Description: Program for examining outcome measurement patterns (and
*				missingness) as well as examining Crude event rates. Computes
*				and categorizes timing of the last measurements for each
*				participant. Allocates measurements to 5 periods in the 
*				post-release/discharge interval [0 to 45 days, 60 to 120 days, 
*				150 to 210 days, 240 to 300 days, and 330 to 390 days] roughly 
*				corresponding to months 1, 3, 6, 9 and 12. For each participant, 
*				indicators are computed to record whether measurements were 
*				planned in each of these periods and whether these planned 
*				measurements were actually completed. Crude event rates for these 
*				periods are also computed. Crude event patterns and measurement 
*				patterns are summarized. Finally, frequencies of the number of
*				positive test results are computed. 
*
*						
* Last modified: July 27, 2015												
* Created by: Martin Wegman													
*****************************************************************************;

ods noproctitle;
%let date = %sysfunc(date(),DATE7.);
options nodate nonumber;
ODS ESCAPECHAR='^'; 

%let dat = data; * Dataset name stem;

%let v = 21; * From compute_anyuse sas file;

data loc.&dat.&v;
	set loc.&in;
run;

****************************************************************************;
****************************************************************************;
********          Examine/print timing of last observation         *********;
****************************************************************************;
****************************************************************************;

%let v2 = %eval(&v + 1);

data loc.&dat.&v2;
	set loc.&dat.&v;

	array F F0--F15;
	array T T0--T15;

	T_last = .;

	do over F;
		if F = 0 then T_last = T;
	end;

	if T_last > 300 then miss_group_a = 4;
	else if T_last > 100 then miss_group_a = 3;
	else if T_last > 30 then miss_group_a = 2;
	else if T_last >= 0 then miss_group_a = 1;
	else miss_group_a = 0;

run;

****************************************************************************;

proc freq data = loc.&dat.&v2 noprint;
	where imp in('c1');
	tables miss_group_a/ out = temp1;
run;

proc freq data = loc.&dat.&v2 noprint;
	where imp in('c2');
	tables miss_group_a/ out = temp2;
run;

proc freq data = loc.&dat.&v2 noprint;
	where imp in('c3');
	tables miss_group_a/ out = temp3;
run;

proc freq data = loc.&dat.&v2 noprint;
	where imp in('p1');
	tables miss_group_a/ out = temp4;
run;

proc freq data = loc.&dat.&v2 noprint;
	where imp in('p2');
	tables miss_group_a/ out = temp5;
run;

proc freq data = loc.&dat.&v2 noprint;
	where imp in('p3');
	tables miss_group_a/ out = temp6;
run;

proc format;

value miss_group_ 	0 = "None"
					1 = "0 to 30 days"
					2 = "31 to 100 days"
					3 = "101 to 300 days"
					4 = ">300 days";
run;

data tempall;
	merge temp1(rename=(count=v1))
		temp2(rename=(count=v2))
		temp3(rename=(count=v3))
		temp4(rename=(count=v4))
		temp5(rename=(count=v5))
		temp6(rename=(count=v6));
	by miss_group_a;

	label v1 = "VTC (SR)";
	label v2 = "VTC (SV90)";
	label v3 = "VTC (SV30)";
	label v4 = "CDDC (SR)";
	label v5 = "CDDC (SV14)";
	label v6 = "CDDC (SV0)";
	label miss_group_a = "Last observation post-release/discharge";
	drop percent;
run;

%let file = "&out_dir.\CDDC Urine Supp last obs &date..rtf";
ods rtf file = &file Style = custom startpage = NO BODYTITLE;

Title 'Table S8. Frequency of the timing of the last completed outcome measurement.';
proc print data = tempall noobs label;
var miss_group_a /style(header data)={just=l};
var v1-v6/style(header data)={just=c}; 
format miss_group_a miss_group_.;
run;
Title;

ods text = "VTC: Voluntary Treatment Center";
ods text = "CDDC: Compulsory Drug Detention Center";
ods text = "SR: Stochastic regression imputation";
ods text = "SV90: Single value imputation of length of inpatient stay (90 days)";
ods text = "SV30: Single value imputation of length of inpatient stay (30 days)";
ods text = "SV14: Single value imputation of time of first outcome measurement (14 days)";
ods text =  "SV0: Single value imputation of time of first outcome measurement (0 days)";

ods rtf close;

****************************************************************************;

* Appears missing discharge date is unrelated to how long participant was under observation;
Proc freq data = loc.&dat.&v2;
	where imp in('c1');
	tables miss_dis*miss_group_a;
run;

****************************************************************************;
* Plot histograms;
/*
proc sgplot data = loc.&dat.&v2;
	by site;
	where urines_observed and imp in('c1','p1');
	histogram T_last /binwidth = 50 ;
run;

proc sgplot data = loc.&dat.&v2;
	by site;
	where urines_observed and imp in('c2','p1');
	histogram T_last /binwidth = 50 ;
run;

proc sgplot data = loc.&dat.&v2;
	by site;
	where urines_observed and imp in('c3','p1');
	histogram T_last /binwidth = 50 ;
run;
*/

****************************************************************************;

* Print to file;

/*
proc format;
value $imp_ 'c1'="VTC (SR)"
			'c2'="VTC (SV90)"
			'c3'="VTC (SV30)"
			'p1'="CDDC";
run;

proc sort data = loc.&dat.&v2; by imp; run;

%let file = "&out_dir.\CDDC Urine Supp last obs timing &date..rtf";
ods rtf file = &file startpage = NO;

Title 'Timing of last observation';
proc sgplot data = loc.&dat.&v2;
	by imp;
	where urines_observed and imp ~in('p2','p3');
	histogram T_last /binwidth = 50 ;
	format imp $imp_.;
	xaxis max = 500;
	yaxis max = 35;
	label T_last = 'Last observation (days since release/discharge)';
	label imp = "Arm";
run;
title;

ods text = "VTC: Voluntary Treatment Center";
ods text = "CDDC: Compulsory Drug Detention Center";
ods text = "SR: Stochastic regression imputation of inpatient days";
ods text = "SV90: Single value imputation of inpatient days (90 days)";
ods text = "SV30: Single value imputation of inpatient days (30 days)";

ods rtf close;

*/

****************************************************************************;
****************************************************************************;
********          Parition post-release/discharge period           *********;
****************************************************************************;
****************************************************************************;

* Partion post-release/discharge time into roughly five periods 
	(month1 month3 month6 month9 month12), then record number 
 	under observation in that window (d_month), who are 
	measured (n_month) and if measured, the observed value (y_var_month); 


%MACRO outcome_periods(v);

%let v2 = %eval(&v + 1);

data loc.&dat.&v2;
	set loc.&dat.&v;
run;

%let list = opi amp bzd thc bup mtd hiv any;

%do i = 1 %to 8;

	%let var = %scan(&list, &i);
	%put &var;

	%let y_list = 	Y0_&var Y1_&var Y2_&var Y3_&var 
					Y4_&var Y6_&var Y9_&var Y12_&var Y15_&var;

	data loc.&dat.&v2;
		set loc.&dat.&v2;

		array F F0--F15;
		array T T0--T15;
		array Y &y_list;

		y_&var._month1 = .;
		y_&var._month3 = .;
		y_&var._month6 = .;
		y_&var._month9 = .;
		y_&var._month12 = .;

		do over T;

				if T >= 0 and T < 45 then do;
					if F in(1,2) and flag1 ~= 1 then do; 
						d_month1 = 1; n_month1 = 0; 
					end;	
					else if F = 0 then do;
						d_month1 = 1; n_month1 = 1; flag1 = 1;
						if y_&var._month1 ~= 1 then y_&var._month1 = Y;
					end;
				end;

				else if T >= 60 and T < 120  then do;
					if F in(1,2) and flag3 ~= 1 then do; 
						d_month3 = 1; n_month3 = 0;
					end;
					else if F = 0 then do; 	
						d_month3 = 1; n_month3 = 1; flag3 = 1; 
						if y_&var._month3 ~= 1 then y_&var._month3 = Y;
					end;
				end;

				else if T >= 150 and T < 210 then do;
					if F in(1,2) and flag6 ~= 1 then do; 	
						d_month6 = 1; n_month6 = 0; 			
					end;
					else if F = 0 then do; 	
						d_month6 = 1; n_month6 = 1; flag6 = 1; 
						if y_&var._month6 ~= 1 then y_&var._month6 = Y;
					end;
				end;

				else if T >= 240 and T < 300  then do;
					if  F in(1,2) and flag9 ~= 1 then do; 	
						d_month9 = 1; n_month9 = 0; 			
					end;
					else if F = 0 	then do; 	
						d_month9 = 1; n_month9 = 1; flag9 = 1;
						if y_&var._month9 ~= 1 then y_&var._month9 = Y;	
					end;
				end;

				else if T >= 330 and T < 390 then do;
					if F in(1,2) and flag12 ~= 1 then do; 	
						d_month12 = 1; n_month12 = 0; 				
					end;
					else if F = 0 	then do; 	
						d_month12 = 1; n_month12 = 1; flag12 = 1;
						if y_&var._month12 ~= 1 then y_&var._month12 = Y;
					end;
				end;

		end;

	run;

%end;

%MEND;


****************************************************************************;

%let v = 22;

%outcome_periods(&v);

/*
* Check result;
%let v2 = %eval(&v + 1);

proc freq data = loc.&dat.&v2; 
	where imp in('c1','p1');
	tables site*(y_opi_month1 n_month1 d_month1)/missprint;
run;

*/

****************************************************************************;
****************************************************************************;
********          Examine/print observations by period             *********;
****************************************************************************;
****************************************************************************;

%MACRO obs_rates(v);

	%let num = 1 3 6 9 12;
	%let k = 1;
	%let val = %scan(&num, &k);
	%let list =;

	proc sort data =  loc.&dat.&v; by imp; run;

	%do %while("&val" NE "");
	
		proc freq data = loc.&dat.&v noprint;
			by imp;
			tables d_month&val/ out=D&val;
			tables n_month&val/ out=N&val;
		run;

		data temp&val;
			length time 3.;
			merge 	N&val (where = (n_month&val = 1) rename = (count = num)) 
					D&val (where = (d_month&val = 1) rename = (count = den));
			by imp;
			retain v1-v6;

			if imp = 'c1' then
				v1 = put(100*num/den,4.1) || "% " || compress("(" || num || "/" || den || ")"," ");
			else if imp = 'c2' then
				v2 = put(100*num/den,4.1) || "% " || compress("(" || num || "/" || den || ")"," ");
			else if imp = 'c3' then
				v3 = put(100*num/den,4.1) || "% " || compress("(" || num || "/" || den || ")"," ");
			else if imp = 'p1' then
				v4 = put(100*num/den,4.1) || "% " || compress("(" || num || "/" || den || ")"," ");
			else if imp = 'p2' then
				v5 = put(100*num/den,4.1) || "% " || compress("(" || num || "/" || den || ")"," ");
			else if imp = 'p3' then
				v6 = put(100*num/den,4.1) || "% " || compress("(" || num || "/" || den || ")"," ");
			
			time = &val;

			if ~(last.imp and imp = "p3") then delete;
			
			keep time v1-v6;

		run;

		%let list = &list temp&val;
		%let k = %eval(&k + 1);
		%let val = %scan(&num, &k);
	%end;

	data loc.obs_rates;
		set &list;
		label v1 = "VTC (SR)";
		label v2 = "VTC (SV90)";
		label v3 = "VTC (SV30)";
		label v4 = "CDDC (SR)";
		label v5 = "CDDC (SV14)";
		label v6 = "CDDC (SV0)";
	run;

%MEND;

****************************************************************************;
%let v = 23;
%obs_rates(&v);

proc format;
value period_ 	1="Month 1 ^n(0 to 45 days)"
				3="Month 3 ^n(60 to 120 days)"
				6="Month 6 ^n(150 to 210 days)"
				9="Month 9 ^n(240 to 300 days)"
				12="Month 12 ^n(330 to 390 days)";
run;

%let file = "&out_dir.\CDDC Urine Supp obs by period &date..rtf";
ods rtf file = &file Style = custom startpage = NO BODYTITLE;

title 'Table S9. Percent of planned outcome measurements completed, by period.';
proc print data = loc.obs_rates noobs label;
var time /style(header data)={just=l};
var v1-v6/style(header data)={just=c};
format time period_.;
label time = "Period post-release/discharge";
run;
title;

%let text = 
"Note: Numerator is number of completed outcome measurements and 
 denominator is number of planned outcome measurements, in the period. 
 Participants with more 
 than one planned measurement per period were counted once, 
 contributing to the numerator if at least one planned measurement 
 was completed. Outcome measurements which did not occur during the 
 specified periods are included in the main analyses described in 
 the manuscript, but are not included in this table.^2n";
ods text = &text;
ods text = "VTC: Voluntary Treatment Center";
ods text = "CDDC: Compulsory Drug Detention Center";
ods text = "SR: Stochastic regression imputation";
ods text = "SV90: Single value imputation of length of inpatient stay (90 days)";
ods text = "SV30: Single value imputation of length of inpatient stay (30 days)";
ods text = "SV14: Single value imputation of time of first outcome measurement (14 days)";
ods text =  "SV0: Single value imputation of time of first outcome measurement (0 days)";

ods rtf close;

****************************************************************************;
****************************************************************************;
****         Examine/print event rates for each period           ***********;
****************************************************************************;
****************************************************************************;

%MACRO out_rates(v,var);

	%let num = 1 3 6 9 12;
	%let k= 1;
	%let val = %scan(&num, &k);
	%let list =;

	proc sort data = loc.&dat.&v; by imp; run;

	%do %while("&val" NE "");

		proc freq data = loc.&dat.&v noprint;
			by imp;
			where n_month&val;
			tables Y_&var._month&val/ out=temp&val;
		run;

		data temp&val;
			length Month 3.;
			set temp&val;
			by imp;
			retain count2 count3 v1-v6;
			
			if first.imp then do;
				count2 = 0;
				count3 = 0;
				flag = .;
			end;

			if Y_&var._month&val = 0 then do;
				count2 = count; flag = 1;
			end;

			else if Y_&var._month&val = 1 then do;
				count3 = count; flag = 1;
			end;

			if last.imp and flag then do;
					if imp = 'c1' then
					v1 = put(100*count3/(count2+count3),4.1) || "% " || compress("(" || count3 || "/" || count2+count3 || ")"," ");
				else if imp = 'c2' then
					v2 = put(100*count3/(count2+count3),4.1) || "% " || compress("(" || count3 || "/" || count2+count3 || ")"," ");
				else if imp = 'c3' then
					v3 = put(100*count3/(count2+count3),4.1) || "% " || compress("(" || count3 || "/" || count2+count3 || ")"," ");
				else if imp = 'p1' then
					v4 = put(100*count3/(count2+count3),4.1) || "% " || compress("(" || count3 || "/" || count2+count3 || ")"," ");
				else if imp = 'p2' then
					v5 = put(100*count3/(count2+count3),4.1) || "% " || compress("(" || count3 || "/" || count2+count3 || ")"," ");
				else if imp = 'p3' then
					v6 = put(100*count3/(count2+count3),4.1) || "% " || compress("(" || count3 || "/" || count2+count3 || ")"," ");
				
			end;
			else if last.imp and flag ~= 1 then do;
				if imp = 'c1' then
					v1 = ". (0/0)";
				else if imp = 'c2' then
					v2 =  ". (0/0)";
				else if imp = 'c3' then
					v3 =  ". (0/0)";
				else if imp = 'p1' then
					v4 =  ". (0/0)";
				else if imp = 'p2' then
					v5 =  ". (0/0)";
				else if imp = 'p3' then
					v6 =  ". (0/0)";
			end;

			month = &val;

			if last.imp and imp = 'p3';

			keep month v1-v6;

		run;

		%let list = &list temp&val;
		%let k = %eval(&k + 1);
		%let val = %scan(&num, &k);

	%end;

	data loc.out_rates;
		set &list;
		label v1 = "VTC (SR)";
		label v2 = "VTC (SV90)";
		label v3 = "VTC (SV30)";
		label v4 = "CDDC (SR)";
		label v5 = "CDDC (SV14)";
		label v6 = "CDDC (SV0)";

		format month period_.;
		label month = "Period post-release/discharge";
	run;

%MEND;

****************************************************************************;
%let v = 23;
 
%let file = "&out_dir.\CDDC Urine Supp event rates by period &date..rtf";
ods rtf file = &file Style = custom_narrow startpage = NO BODYTITLE;

%let var = opi;
%out_rates(&v,&var);
Title 'Table S10a. Crude drug use rates (opiates) by period.';  
proc print data = loc.out_rates noobs label;
var Month /style(header data)={just=l};
var v1-v6/style(header data)={just=c};
run;

%let var = amp;
%out_rates(&v,&var); 
Title 'Table S10b. Crude drug use rates (amphetamines) by period.'; 
proc print data = loc.out_rates noobs label;
var Month /style(header data)={just=l};
var v1-v6/style(header data)={just=c};
run;

ods startpage = now;

%let var = bzd;
%out_rates(&v,&var);
Title 'Table S10c. Crude drug use rates (benzodiazepines) by period.';  
proc print data = loc.out_rates noobs label;
var Month /style(header data)={just=l};
var v1-v6/style(header data)={just=c};
run;

%let var = any;
%out_rates(&v,&var);
Title 'Table S10d. Crude drug use rates (any illicit drug) by period.'; 
proc print data = loc.out_rates noobs label;
var Month /style(header data)={just=l};
var v1-v6/style(header data)={just=c};
run;

ods startpage = now;

%let var = mtd;
%out_rates(&v,&var);
Title 'Table S10e. Crude methadone use rates by period.'; 
proc print data = loc.out_rates noobs label;
var Month /style(header data)={just=l};
var v1-v6/style(header data)={just=c};
run;
/*
%let var = hiv;
%out_rates(&v,&var);
Title 'Table S10f. Crude HIV prevalence by period.'; 
proc print data = loc.out_rates noobs label;
var Month /style(header data)={just=l};
var v1-v6/style(header data)={just=c};
run;*/
title;
%let text = 
"^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}
Note: Numerator is number of participants with a positive test result
 and denominator is number of participants with a test result, 
 in the period for a given metabolite. For a given period and metabolite, 
 participants with more than one outcome measurement were counted once, contributing 
 to the numerator if at least one measurement was positive.
 Observations which did not occur during any of the periods were 
 excluded from these tables.^2n";
ods text = &text;
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}VTC: Voluntary Treatment Center";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}CDDC: Compulsory Drug Detention Center";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SR: Stochastic regression imputation";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV90: Single value imputation of length of inpatient stay (90 days)";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV30: Single value imputation of length of inpatient stay (30 days)";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV14: Single value imputation of time of first outcome measurement (14 days)";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV0: Single value imputation of time of first outcome measurement (0 days)";

ods rtf close;

****************************************************************************;
****************************************************************************;
******      Look at patterns of missingness over month 1,3,6,9,12   ********;
****************************************************************************;
****************************************************************************;

%let v = 23;
%let v2 = %eval(&v + 1);
%let months_list = n_month1 n_month3 n_month6 n_month9 n_month12;

data loc.&dat.&v2;
	length pattern1 $ 6;
	length pattern2 $ 6;
	set loc.&dat.&v;
	
	array x &months_list;

	do over x;
			 if x = 0 then pattern1 = trim(pattern1) || '_';
		else if x = 1 then pattern1 = trim(pattern1) || '*';
		else pattern1 = trim(pattern1) || '0';

			if x = 0 then pattern2 = trim(pattern2) || '_';
		else if x = 1 then pattern2 = trim(pattern2) || '*';
		else pattern2 = trim(pattern2) || '_';
	end;

	Arm = imp;
	Pattern = pattern2;

run;


****************************************************************************;

proc sort data = loc.&dat.&v2; by Arm; run;

proc format;

value $imp_	 	'c1'='VTC (SR)'
				'c2'='VTC (SV90)'
				'c3'='VTC (SV30)'
				'p1'='CDDC (SR)'
				'p2'='CDDC (SV14)'
				'p3'='CDDC (SV0)';
run;

%let file = "&out_dir.\CDDC Urine Supp obs patterns &date..rtf";
ods rtf file = &file Style = custom startpage = NO BODYTITLE;

Title 'Table S11. Frequencies of various outcome measurement patterns.';

proc tabulate data =  loc.&dat.&v2 S=[just=c];
    /* Specify the variables to investigate */
    class pattern arm; 
    table
        /* Put x in the rows suppress its title and add a total row */
        pattern = "", 
        /* Put y in the columns, request a total, request frequency count*/
        (arm) * n = "" / 
            /* Put "x" in the top left box */
            box = {label='Pattern' s=[Just=L]};
			format arm $imp_.;
	label arm="Group";
run;
title;

%let text =
"Notes: * indicates a measurement in a given period, 
 _ indicates a missed or an untargeted period.
 Outcome measurements not occuring during a period are 
 not included in these patterns.^2n";
ods text = &text;
ods text = "VTC: Voluntary Treatment Center";
ods text = "CDDC: Compulsory Drug Detention Center";
ods text = "SR: Stochastic regression imputation";
ods text = "SV90: Single value imputation of length of inpatient stay (90 days)";
ods text = "SV30: Single value imputation of length of inpatient stay (30 days)";
ods text = "SV14: Single value imputation of time of first outcome measurement (14 days)";
ods text =  "SV0: Single value imputation of time of first outcome measurement (0 days)";


ods rtf close;

****************************************************************************;
****************************************************************************;
******      Look at patterns of outcomes over month 1,3,6,9,12    ********;
****************************************************************************;
****************************************************************************;

%MACRO out_patterns (v,var);

%let y_list = 	Y_&var._month1 Y_&var._month3 
				Y_&var._month6 Y_&var._month9 Y_&var._month12;

data loc.&dat.&v;
	length pattern1_&var $ 6;
	length pattern2_&var $ 6;
	set loc.&dat.&v;
	
	array x &y_list;

	do over x;
			 if x = 0 then pattern1_&var = trim(pattern1_&var) || '_';
		else if x = 1 then pattern1_&var = trim(pattern1_&var) || '*';
		else pattern1_&var = trim(pattern1_&var) || '0';

			if x = 0 then pattern2_&var = trim(pattern2_&var) || '_';
		else if x = 1 then pattern2_&var = trim(pattern2_&var) || '*';
		else pattern2_&var = trim(pattern2_&var) || '_';

	end;

	Pattern = pattern2_&var;

run;

proc sort data = loc.&dat.&v2; by Arm; run;

proc tabulate data =  loc.&dat.&v2 S=[just=c];
    /* Specify the variables to investigate */
    class pattern arm; 
    table
        /* Put x in the rows suppress its title and add a total row */
        pattern = "", 
        /* Put y in the columns, request a total, request frequency count*/
        (arm) * n = "" / 
            /* Put "x" in the top left box */
            box = {label='Pattern' s=[Just=L]};
			format arm $imp_.;
	label arm="Group";
run;

%MEND;

****************************************************************************;

%let v = 24;
%let v2 = %eval(&v + 1);

data loc.&dat.&v2;
	set loc.&dat.&v;
run;

****************************************************************************;
%let file = "&out_dir.\CDDC Urine Supp event patterns &date..rtf";
ods rtf file = &file Style = custom_narrow startpage = NO BODYTITLE;

Title "Table S12a. Patterns of opiate use."; 
%let var = opi;
%out_patterns(&v2,&var);

ods rtf STARTPAGE= NOW;
Title "Table S12b. Patterns of amphetamine use."; 
%let var = amp;
%out_patterns(&v2,&var);

/*ods rtf STARTPAGE= NOW;
Title "Table S12c. Patterns of benzodiazapine use."; 
%let var = bzd;
%out_patterns(&v2,&var);*/

ods rtf STARTPAGE= NOW;
Title "Table S12c. Patterns of any illict drug use."; 
%let var = any;
%out_patterns(&v2,&var);

ods rtf STARTPAGE= NOW;
Title "Table S12d. Patterns of methadone use."; 
%let var = mtd;
%out_patterns(&v2,&var);

%let text =
"^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}
Note: * indicates a positive test in a given period, _ indicates a negative,
 a missed or an untargeted period. Outcome measurements not 
 occuring during a period are not included in these patterns.^2n";
ods text = &text;
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}VTC: Voluntary Treatment Center";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}CDDC: Compulsory Drug Detention Center";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SR: Stochastic regression imputation";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV90: Single value imputation of length of inpatient stay (90 days)";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV30: Single value imputation of length of inpatient stay (30 days)";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV14: Single value imputation of time of first outcome measurement (14 days)";
ods text = "^S={LEFTMARGIN = 1in RIGHTMARGIN = 1in}SV0: Single value imputation of time of first outcome measurement (0 days)";

ods rtf close;

****************************************************************************;
****************************************************************************;
*************  Count number of positve urines for each record  *************;
****************************************************************************;
****************************************************************************;

%MACRO count_outcomes (v);

%let v2 = %eval(&v + 1);

data loc.&dat.&v2;
	set loc.&dat.&v;
run;

%let list = opi amp bzd thc bup mtd hiv any;

%do i = 1 %to 8;

	%let var = %scan(&list, &i);
	%put &var;

	%let y_list = 	Y0_&var Y1_&var Y2_&var Y3_&var 
						Y4_&var Y6_&var Y9_&var Y12_&var Y15_&var;

	data loc.&dat.&v2;
		set loc.&dat.&v2;

		array y &y_list;

		count_&var = 0;

		do over y;
			if y = 1 then count_&var = count_&var + 1;
		end;
	run;

%end;

%MEND;

%let v = 25;

%count_outcomes(&v);


%MACRO print_counts(v,var);

proc tabulate data =  loc.&dat.&v S=[just=c];
    /* Specify the variables to investigate */
    class count_&var arm; 
    table
        /* Put x in the rows suppress its title and add a total row */
        count_&var = "", 
        /* Put y in the columns, request a total, request frequency count*/
        (arm) * n = "" / 
            /* Put "x" in the top left box */
            box = {label='Number of positive measurements' s=[Just=L]};
			format arm $imp_.;
			label arm="Group";
run;

%MEND;

%let file = "&out_dir.\CDDC Urine Supp opiate urine counts &date..rtf";
ods rtf file = &file Style = custom startpage = NO BODYTITLE;

title "Table S13a. Frequency of participants with various opiate-positive urine measurement counts.";
%let var = opi;
%print_counts(&v2,&var);

title "Table S13b. Frequency of participants with various amphetamine-positive urine measurement counts.";
%let var = amp;
%print_counts(&v2,&var);

title "Table S13c. Frequency of participants with various illicit-drug-positive urine measurement counts.";
%let var = any;
%print_counts(&v2,&var);

ods startpage = now;

title "Table S13d. Frequency of participants with various methadone-positive urine measurement counts.";
%let var = mtd;
%print_counts(&v2,&var);

title "Table S13e. Frequency of participants with various benzodiazapine-positive urine measurement counts.";
%let var = bzd;
%print_counts(&v2,&var);

title "Table S13f. Frequency of participants with various buprenorphine-positive urine measurement counts.";
%let var = bup;
%print_counts(&v2,&var); 

/*ods startpage = now;

title "Table S13f. Frequency of participants with various hiv-positive measurement counts.";
%let var = hiv;
%print_counts(&v2,&var); */
title;

ods text = "VTC: Voluntary Treatment Center";
ods text = "CDDC: Compulsory Drug Detention Center";
ods text = "SR: Stochastic regression imputation";
ods text = "SV90: Single value imputation of length of inpatient stay (90 days)";
ods text = "SV30: Single value imputation of length of inpatient stay (30 days)";
ods text = "SV14: Single value imputation of time of first outcome measurement (14 days)";
ods text =  "SV0: Single value imputation of time of first outcome measurement (0 days)";


ods rtf close;


data loc.&out;
	set loc.&dat.&v2;
run;


****************************************************************************;
****************************************************************************;
*********************   Remove old datasets               ******************;
****************************************************************************;
****************************************************************************;


proc datasets lib=loc nolist;       
	delete &dat.21 - &dat.26 obs_rates out_rates;   
run;
quit;


****************************************************************************;
****************************************************************************;
**************                END                ***************************;
****************************************************************************;
****************************************************************************;

%MEND patterns;
